package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName $ {NAME}
 * @Description TODO
 * @Author 寇铭
 * @Date 2022/6/15 20:51
 * @Version 1.0
 **/
@Service
public class AddressServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Autowired
    private OrderService orderService;

    //删除地址，如果该地址关联订单则不能删除
    @Override
    public void removeAddress(Long[] ids) {

        List<Long> addressIds = new ArrayList<>();
        for (Long id : ids) {
            addressIds.add(id);
        }
        //查询当前地址是否关联订单，如果关联不能删除
        for (Long addressId : addressIds) {
            LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Orders::getAddressBookId, addressId);
            int count = orderService.count(queryWrapper);

            if (count > 0) {
                throw new CustomException("当前地址关联订单，不能删除。");
            }
        }

        this.removeByIds(addressIds);


    }
}
